package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.SaveDeviceAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Key;
import com.dotstone.chipism.bean.Order;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.MyDBHelper;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.MyListView;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FirstSetupActivity1 extends BaseActivity {
	private LinearLayout mBackL;
	private Button mRepublishB;
	private Button mAddWlanB;
	private Button mAddDeviceB;
	private MyListView mDeviceL;
	private Button mSaveB;
	private TextView tv_statusBar_mian;
	private List<Device> mWlans = new ArrayList<Device>();
	private List<Device> mDevices = new ArrayList<Device>();
	private SaveDeviceAdapter mAdapter;
	private SVProgressHUD mSVProgressHUD;
	private int mUpLoadCounts = 0;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private int deleteCount = 0;
	private int deviceCount;
	private EditText pwdEd;
	private Dialog mDialog;
	private Order order;
	private MyDBHelper myDBHelper;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			// 如果保存了网关 需要将网关删除
			if (mDevices.size() == 0) {
				if (PairWlanActivity.pairWlanActivity != null) {
					PairWlanActivity.pairWlanActivity.finish();
				}
				finish();
			} else {
				showAskDialog();
			}
			break;
		case R.id.re_publish_btn:
			// 跳转至发布订单界面
			if (order.getStatus() == 8) {
				Intent intent = new Intent(getApplicationContext(), PublishOrderActivity.class);
				startActivity(intent);
			} else if (order.getStatus() == 2) {
				Intent intent = new Intent(getApplicationContext(), PublishOrderActivity1.class);
				startActivity(intent);
			}
			finish();
			break;
		case R.id.add_device_b:
			// 添加设备前 先检查是否有网关 如果有 跳转至选择网关界面
			// 再跳转至二维码扫描界面
			// 如果没有 吐司提示
			if (DeviceManager.getInstance().getCurrentOrder().getStatus() == 8) {
				ToastShow.Show(getApplicationContext(), "工单尚未被受理，无法私自安装");
				return;
			}
			if (DeviceManager.getInstance().getWlans().size() != 0) {
				// 检查版本
				// 检查权限
				// 如果没有权限 弹出提示 由于无法判断用户是否选了不再提示 所以直接每次都弹出提示框询问用户是否启用摄像头
				if (Build.VERSION.SDK_INT >= 23) {
					if (ContextCompat.checkSelfPermission(getApplicationContext(),
							Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						// 不能使用 调用以下方法申请摄像头权限
						ActivityCompat.requestPermissions(FirstSetupActivity1.this,
								new String[] { Manifest.permission.CAMERA }, 0);
						// 同时要弹出提示框提醒
						askPermission(Manifest.permission.CAMERA);
					} else {
						Intent intent1 = new Intent(getApplicationContext(), CaptureActivity.class);
						intent1.putExtra("entry", 2);
						startActivity(intent1);
					}
				} else {
					Intent intent1 = new Intent(getApplicationContext(), CaptureActivity.class);
					intent1.putExtra("entry", 2);
					startActivity(intent1);
				}
			} else {
				ToastShow.Show(getApplicationContext(), getString(R.string.wlan_first));
			}
			break;
		case R.id.add_wlan_b:
			if (DeviceManager.getInstance().getCurrentOrder().getStatus() == 8) {
				ToastShow.Show(getApplicationContext(), "工单尚未被受理，无法私自安装");
				return;
			}
			Intent intent2 = new Intent(getApplicationContext(), PairWlanActivity.class);
			startActivity(intent2);
			break;
		case R.id.save_btn:
			// 上传服务器
			// finish();
			if (DeviceManager.getInstance().getCurrentOrder().getStatus() == 8) {
				ToastShow.Show(getApplicationContext(), "工单尚未被受理，无法私自安装");
				return;
			}
			mDevices = mAdapter.getData();
			if (mDevices.size() == 0) {
				ToastShow.Show(getApplicationContext(), getString(R.string.no_add_device));
				return;
			}
			mNormalDialog = new NormalDialog(FirstSetupActivity1.this);
			mNormalDialog.content("是否结束本次安装？").style(NormalDialog.STYLE_TWO)//
					.titleTextSize(18)//
					.showAnim(bas_in)//
					.dismissAnim(bas_out)//
					.show();
			mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
				@Override
				public void onBtnClick() {
					mNormalDialog.dismiss();
				}
			}, new OnBtnClickL() {
				@Override
				public void onBtnClick() {
					mNormalDialog.dismiss();
					confirm();
				}
			});
			break;

		default:
			break;
		}
	}

	private void confirm() {
		mDialog = new Dialog(FirstSetupActivity1.this, R.style.popupDialog3);
		mDialog.setContentView(R.layout.dialog_pwd1);
		TextView order = (TextView) mDialog.findViewById(R.id.order_tv);
		pwdEd = (EditText) mDialog.findViewById(R.id.pwd_ed);
		Button mOkB = (Button) mDialog.findViewById(R.id.ok);
		order.setText("订单：订单" + DeviceManager.getInstance().getCurrentOrder().getId());
		mOkB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String pwd = pwdEd.getText().toString();
				if (pwd != null) {
					String pwd1 = (String) SPUtils.get(getApplicationContext(), "pwd", "");
					if (pwd1.equals(pwd)) {
						finishOrder();
						mDialog.dismiss();
					} else {
						ToastShow.Show(getApplicationContext(), getString(R.string.errorpassword));
					}
				} else {
					ToastShow.Show(getApplicationContext(), getString(R.string.pwd_not_null));
				}
			}
		});
		mDialog.show();
	}

	private void showAskDialog() {
		mNormalDialog = new NormalDialog(FirstSetupActivity1.this);
		mNormalDialog.content("正在进行安装，是否取消本次安装？").style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				// saveLight1();
				deleteAllDevices();
				SocketManager.getInstance().sMap.clear();
				// finishOrder();
			}
		});
	}

	private void deleteAllDevices() {
		mSVProgressHUD = new SVProgressHUD(FirstSetupActivity1.this);
		mSVProgressHUD.showWithStatus("正在撤销安装");
		deviceCount = mDevices.size();
		for (int i = 0; i < mDevices.size(); i++) {
			deleteDevice(mDevices.get(i));
		}
		// finish();
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (deleteCount != deviceCount) {
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
					DeviceManager.getInstance().clearDevice();

					ToastShow.Show(getApplicationContext(), "取消安装");
					if (PairWlanActivity.pairWlanActivity != null) {
						PairWlanActivity.pairWlanActivity.finish();
					}
					finish();
				}
			}
		}, 5 * 1000);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mDevices.size() == 0) {
				if (PairWlanActivity.pairWlanActivity != null) {
					PairWlanActivity.pairWlanActivity.finish();
				}
				finish();
			} else {
				showAskDialog();
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				int count = msg.arg1;
				count++;
				if (count < mDevices.size()) {
					upLoadDevices(count);
				} else {
					// Toast.makeText(getApplicationContext(), "设备绑定成功！",
					// Toast.LENGTH_SHORT).show();
					// mDevices.clear();
					// finish();
					finishOrder();
				}
				break;
			case 2:
				// finish();
				break;
			case 3:
				SocketManager.getInstance().initSocket(getApplicationContext());
				mWlans = DeviceManager.getInstance().getWlans();
				for (int i = 0; i < mWlans.size(); i++) {
					boolean e = false;
					for (Device d : mDevices) {
						if (d.getDeviceAddress().equals(mWlans.get(i).getDeviceAddress())) {
							e = true;
						}
					}
					if (!e) {
						mDevices.add(mWlans.get(i));
					}
				}
				if (mAdapter == null) {
					Log.i("wmy", "mAdapter为空");
					mAdapter = new SaveDeviceAdapter(getApplicationContext(), mDevices);
					mDeviceL.setAdapter(mAdapter);
				} else {
					Log.i("wmy", "mAdapter不为空");
					mAdapter.notifyDataSetChanged();
				}

				break;
			case 4:
				Toast.makeText(getApplicationContext(), "设备绑定成功！", Toast.LENGTH_SHORT).show();
				mDevices.clear();
				DeviceManager.getInstance().clearSaveDevice();
				DeviceManager.getInstance().setCurrentOrder(new Order());
				DeviceManager.getInstance().setmSaveWlan(null);
				if (PairWlanActivity.pairWlanActivity != null) {
					PairWlanActivity.pairWlanActivity.finish();
				}
				finish();
				break;
			case 5:
				mDevices = DeviceManager.getInstance().getAllDevice();
				SocketManager.getInstance().initSocket(getApplicationContext());
				Log.i("wmy", "mDevices.size() = " + mDevices.size());
				if (mAdapter == null) {
					mAdapter = new SaveDeviceAdapter(getApplicationContext(), mDevices);
					mDeviceL.setAdapter(mAdapter);
				} else {
					mAdapter.notifyDataSetChanged();
				}
				break;
			case 6:
				deleteCount++;
				Log.i("wmy", "删除一个设备" + deleteCount + " " + deviceCount);
				if (deleteCount == deviceCount) {
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
					ToastShow.Show(getApplicationContext(), "取消安装");
					DeviceManager.getInstance().clearDevice();
					if (PairWlanActivity.pairWlanActivity != null) {
						PairWlanActivity.pairWlanActivity.finish();
					}
					finish();
				}
				break;
			default:
				break;
			}
		}
	};

	private void finishOrder() {
		RequestParams params = new RequestParams(HttpURL.SCORE_ORDER_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("handlType", 1);
			obj.put("id", DeviceManager.getInstance().getCurrentOrder().getId());
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.e("wmy", " finish order = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("wmy", "finish order result " + result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						Message msg = Message.obtain();
						msg.what = 4;
						mHandler.sendMessage(msg);
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {
				Log.i("wmy", "finish order result cancel" );
			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				Log.i("wmy", "finish order result error" );
			}

			@Override
			public void onFinished() {
				Log.i("wmy", "finish order result onFinished" );
			}

		});
	}

	private void upLoadDevices(final int i) {
		final Device device = mDevices.get(i);
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			if (device.getDeviceAddress() != null) {
				obj.put("deviceAddress", device.getDeviceAddress().toUpperCase());
			}
			obj.put("deviceModel", device.getDeviceName());
			obj.put("deviceName", device.getDeviceName());
			obj.put("deviceType", device.getDeviceType() + "");
			obj.put("deviceVersion", "1.0");
			obj.put("deviceWifiSSID", DeviceManager.getInstance().getmWlanBssid());
			obj.put("deviceId", "0");
			obj.put("hid", DeviceManager.getInstance().hid);
			if (device.getDeviceType() == DeviceType.DEVICE_TYPE_SWITCH
					|| device.getDeviceType() == DeviceType.DEVICE_TYPE_RGB_LIGHT
					|| device.getDeviceType() == DeviceType.DEVICE_TYPE_SOCKET
					|| device.getDeviceType() == DeviceType.DEVICE_TYPE_LOCK) {
				obj.put("mainDeviceId", device.getMainDeviceId());
			} else {
				obj.put("mainDeviceId", "0");
			}
			switch (device.getDeviceType()) {
			case DeviceType.DEVICE_TYPE_SOCKET:
				obj.put("productId", "3");
				obj.put("classification", "2");
				break;
			case DeviceType.DEVICE_TYPE_RGB_LIGHT:
				obj.put("productId", "2");
				obj.put("classification", "2");
				break;
			case DeviceType.DEVICE_TYPE_SWITCH:
				obj.put("productId", "6");
				obj.put("classification", "2");
				break;
			case DeviceType.DEVICE_TYPE_LOCK:
				obj.put("productId", "5");
				obj.put("classification", "5");
				break;
			default:
				break;
			}
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", "save upload device = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					// if (resultCode.equals("1")) {
					// 上传成功，保存到本地
					Message msg = Message.obtain();
					msg.what = 1;
					msg.arg1 = i;
					mHandler.sendMessage(msg);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void checkWlan() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_DEVICE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearDevice();
							JSONArray data = jsonObject.getJSONArray("data");
							Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject deviceInfo = data.getJSONObject(i).getJSONObject("deviceInfo");
									String deviceId = deviceInfo.getString("deviceId");
									String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
									String deviceAddress = deviceInfo.optString("deviceAddress");
									int deviceType = deviceInfo.getInt("deviceType");
									String deviceModel = deviceInfo.getString("deviceModel");
									String deviceName = data.getJSONObject(i).getString("remarks");// deviceName
									int status = deviceInfo.optInt("deviceStatus");
									String mainDeviceId = deviceInfo.optString("mainDeviceId");
									int role = data.getJSONObject(i).optInt("role");
									String userId = deviceInfo.getString("userId");
									Device device = new Device();
									device.setDeviceID(deviceId);
									device.setDeviceWifiSsid(deviceWifiSSID);
									device.setDeviceType(deviceType);
									device.setDeviceBrand(deviceModel);
									device.setDeviceName(deviceName);
									device.setStatus(status);
									Log.i("wmy", deviceName + " 获取设备状态 " + status);
									device.setRole(role);
									device.setUserId(userId);
									if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
										device.setMainDeviceId(mainDeviceId);
									}
									device.setDeviceAddress(deviceAddress);
									DeviceManager.getInstance().addDevice(device);
								}
							}
							Message msg = Message.obtain();
							msg.what = 3;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							DeviceManager.getInstance().setmSaveWlan(null);
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {

				}
			});
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e("wmy", "首次安装onresume mDevices.size()" + mDevices.size());
		getAllDevice();
		if (order.getInstallerTime() < System.currentTimeMillis()) {
			mRepublishB.setText(getString(R.string.published1));
		} else if (order.getStatus() == 8 || order.getStatus() == 2) {
			mRepublishB.setText(getString(R.string.change_order));
		}
	}

	private void addWlan() {
		for (int i = 0; i < mWlans.size(); i++) {
			boolean e = false;
			for (Device d : mDevices) {
				if (d.getDeviceAddress().equals(mWlans.get(i).getDeviceAddress())) {
					e = true;
				}
			}
			if (!e) {
				mDevices.add(mWlans.get(i));
			}
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_first_setup;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		mRepublishB = $(R.id.re_publish_btn);
		mAddDeviceB = $(R.id.add_device_b);
		mAddWlanB = $(R.id.add_wlan_b);
		mDeviceL = $(R.id.device_lv);
		mSaveB = $(R.id.save_btn);
		order = DeviceManager.getInstance().getCurrentOrder();
		if (order.getInstallerTime() < System.currentTimeMillis()) {
			mRepublishB.setText(getString(R.string.published1));
		} else if (order.getStatus() == 8 || order.getStatus() == 2) {
			mRepublishB.setText(getString(R.string.change_order));
		}
		boolVersion();
		mBackL.setOnClickListener(this);
		mRepublishB.setOnClickListener(this);
		mAddDeviceB.setOnClickListener(this);
		mAddWlanB.setOnClickListener(this);
		mSaveB.setOnClickListener(this);
		mDeviceL.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);
		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	private void askPermission(String permission) {
		String request = "";
		if (permission.equals(Manifest.permission.CAMERA)) {
			request = "摄像头权限被禁止，是否开启摄像头？";
		}
		mNormalDialog = new NormalDialog(FirstSetupActivity1.this);
		mNormalDialog.content(request).style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				Intent localIntent = new Intent();
				localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
				localIntent.setData(Uri.fromParts("package", getPackageName(), null));
				startActivity(localIntent);
			}
		});
	}

	private void deleteDevice(final Device device) {
		String deviceID = device.getDeviceID();
		if (deviceID.equals("")) {
			return;
		} else {
			if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.DELETE_DEVICE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("deviceId", device.getDeviceID());
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.e("wmy", "delete " + device.getDeviceName() + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "delete =" + device.getDeviceName() + " " + result);
					// deleteLocal();
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							deleteLocal(device);
							Message message = Message.obtain();
							message.what = 6;
							mHandler.sendMessage(message);
						} else {
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {

				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {

				}

				@Override
				public void onFinished() {

				}
			});
		}

	}

	private void deleteLocal(Device device) {
		DeviceManager.getInstance().deleteDevice(device);
		if (SocketManager.getInstance().sMap.get(device.getDeviceID()) != null) {
			SocketManager.getInstance().sMap.get(device.getDeviceID()).stopLocalTcpClient();
			SocketManager.getInstance().sMap.remove(device.getDeviceID());
		}
	}

	public void getAllDevice() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_DEVICE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.e("test", " get all device = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// DeviceManager.getInstance().clearDevice();
					Log.e("wmy", "get all device =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearDevice();
							JSONArray data = jsonObject.getJSONArray("data");
							// Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject deviceInfo = data.getJSONObject(i).getJSONObject("deviceInfo");
									String deviceId = deviceInfo.getString("deviceId");
									String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
									String deviceAddress = deviceInfo.optString("deviceAddress");
									int deviceType = deviceInfo.getInt("deviceType");
									String deviceModel = deviceInfo.getString("deviceModel");
									String deviceName = data.getJSONObject(i).getString("remarks");// deviceName
									int status = deviceInfo.optInt("deviceStatus");
									String mainDeviceId = deviceInfo.optString("mainDeviceId");
									int role = data.getJSONObject(i).optInt("role");
									String userId = deviceInfo.getString("userId");
									Device device = new Device();
									device.setDeviceID(deviceId);
									device.setDeviceWifiSsid(deviceWifiSSID);
									device.setDeviceType(deviceType);
									device.setDeviceBrand(deviceModel);
									device.setDeviceName(deviceName);
									Log.i("wmy", deviceName + " 获取设备状态 " + status);
									device.setStatus(status);
									device.setRole(role);
									device.setUserId(userId);

									if (deviceType == DeviceType.DEVICE_TYPE_AIR_CONTROLLER
											|| deviceType == DeviceType.DEVICE_TYPE_BOX2
											|| deviceType == DeviceType.DEVICE_TYPE_DVD
											|| deviceType == DeviceType.DEVICE_TYPE_FAN
											|| deviceType == DeviceType.DEVICE_TYPE_TV
											|| deviceType == DeviceType.DEVICE_TYPE_PROJECTOR) {
										// 是遥控器
										JSONArray ja = data.getJSONObject(i).getJSONArray("deviceButton");
										List<Key> keys = new ArrayList<Key>();
										for (int n = 0; n < ja.length(); n++) {
											Key key = new Key();
											JSONObject joKey = ja.getJSONObject(n);
											key.setKeyNum(joKey.getInt("position"));
											key.setCodeValue(joKey.getString("buttonCmd"));
											keys.add(key);
										}
										device.setKeys(keys);
									}
									if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
										device.setMainDeviceId(mainDeviceId);
									}
									device.setDeviceAddress(deviceAddress);
									DeviceManager.getInstance().addDevice(device);
								}
							}
							Message msg = Message.obtain();
							msg.what = 5;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

}